package cn.com.template.controller.project;

import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.commons.Paginator;
import cn.com.dal.dataobject.cs.NewProjectDO;
import cn.com.dal.dataobject.cs.NewProjectDetailDO;
import cn.com.dal.dataobject.cs.ProjectDO;
import cn.com.dal.dataobject.hr.DeptDO;
import cn.com.dal.dataobject.sys.DictDO;
import cn.com.service.cs.NewProjectDetailService;
import cn.com.service.cs.NewProjectService;
import cn.com.service.cs.ProjectService;
import cn.com.service.hr.DeptService;
import cn.com.service.sys.DictService;
import cn.com.support.context.UserContext;
import cn.com.support.message.MessageCodeEnum;
import cn.com.support.message.MessageResult;
import cn.com.support.utils.JacksonUtil;
import cn.com.support.utils.TemplateUtils;
import cn.com.template.ui.Flexigrid;
import cn.com.template.utils.FlexigridUtil;

/**
 * 
 * 公司项目管理控制器[修改版]
 * 
 * @since 1.0 2012-8-31 下午11:03:53
 * @version 1.0
 * @author Zoe
 */
@Controller
@RequestMapping("/project/newproject")
public class NewProjectController {

	@Autowired
	private ProjectService projectService;
	@Autowired
	private DeptService deptService;
	@Autowired
	private DictService dictService;
	@Autowired
	private NewProjectService newproService;
	@Autowired
	private NewProjectDetailService newproDetailService;
	/**
	 * 跳转页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping
	public ModelAndView forward(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("/project/newproject");
		DeptDO deptDO = deptService.selectById(UserContext.getUser().getDeptId());
		DictDO dictDO = new DictDO();
		if(null != deptDO){
			dictDO.setModule(deptDO.getName());
		}
		List<DictDO> dictLst = dictService.selectList(dictDO);
		dictDO = new DictDO();
		dictDO.setModule("经营项目");
		List<DictDO> otherdictLst = dictService.selectList(dictDO);
		request.setAttribute("dictLst", dictLst);
		request.setAttribute("otherdictLst", otherdictLst);
		return mav;
	}

	/**
	 * 删除数据
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public MessageResult<Long> delete(HttpServletRequest request) {
		return projectService.deleteById(TemplateUtils.getParams(Long.class,
				request, "id"));
	}

	/**
	 * 查询所有
	 * 
	 * @param condition
	 *            查询条件
	 * @return
	 */
	@RequestMapping("/selectList")
	@ResponseBody
	public List<?> selectList(HttpServletRequest request,
			HttpServletResponse response) {
		return projectService.selectList(TemplateUtils.bulidBeanMap(request,
				ProjectDO.class));
	}

	/**
	 * 根据ID查询
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/selectById")
	@ResponseBody
	public MessageResult<ProjectDO> selectById(@RequestParam("id") Long id) {
		return projectService.selectById(id);
	}

	@RequestMapping("/selectDetail")
	@ResponseBody
	public MessageResult selectDetail(@RequestParam Long pid, String type, String date) {
		MessageResult result = null;
		NewProjectDetailDO projectDetailDO = new NewProjectDetailDO();
		Map<Object, Object> params = new HashMap<Object, Object>();
		params.put("projectId", pid);
		params.put("type", type);
		params.put("gmtRefund", date);
		//当为核算时
		Long outsideCost = null;
		Long conferenceCost = null;
		if("2".equals(type)){
			if(!"".equals(date)){
				params.put("startTime", date+"-01");
				params.put("endTime", date+"-31");
			}
			outsideCost = newproService.selectOutsidecost(params);
			//outsideCost = (null == outsideCost?0L:outsideCost);
			conferenceCost = newproService.selectConferencecost(params);
			//conferenceCost = (null == conferenceCost?0L:conferenceCost);
		}
		List<NewProjectDetailDO> resultLst = newproDetailService.selectList(params);
		if(resultLst != null && resultLst.size()>0){
			projectDetailDO = resultLst.get(0);
			if(null != outsideCost){
				projectDetailDO.setOutsideCost(outsideCost);
			}
			if(null != conferenceCost){
				projectDetailDO.setConferenceCost(conferenceCost);
			}
			result = new MessageResult<NewProjectDetailDO>(true, projectDetailDO, MessageCodeEnum.INFO_SUCCEED);
		}else{
			if(null != outsideCost ){
				projectDetailDO.setOutsideCost(outsideCost);
			}
			if(null != conferenceCost ){
				projectDetailDO.setConferenceCost(conferenceCost);
			}
			result = new MessageResult<NewProjectDetailDO>(false, projectDetailDO, MessageCodeEnum.INFO_SUCCEED);
		}
		return result;
	}
	
	/**
	 * 分页查询
	 * 
	 * @param paginator
	 * @return
	 */
	@RequestMapping("/selectForPage.json")
	@ResponseBody
	public Flexigrid selectForPage(HttpServletRequest request,
			HttpServletResponse response) {
		// 封装参数
		Paginator<Object, List<NewProjectDO>> paginator = new Paginator<Object, List<NewProjectDO>>();
		Integer page = TemplateUtils.getParam(Integer.class, request, "page", 1);
		Map<Object, Object> condition = TemplateUtils.bulidBeanMap(request,
				ProjectDO.class);
		// 封装查询时间
		TemplateUtils.wappedStartAndEndTime(condition, request);
		paginator.setCurrentPage(page);
		paginator.setCondition(condition);
		// 分页查询
		newproService.selectByPage(paginator);
		// 返回结果
		return FlexigridUtil.formatFlexigridData(paginator);
	}

	/**
	 * 更新项目
	 * 
	 * @param projectDO
	 * @return
	 */
	@RequestMapping("/updateById")
	@ResponseBody
	MessageResult<Object> updateById(HttpServletRequest request) {
		@SuppressWarnings("rawtypes")
		MessageResult result = null;
		// 封装参数
		NewProjectDO projectDO = null;
		NewProjectDetailDO detailDO = null;
		try {
			String username = UserContext.getUsername();
			String projectdata = request.getParameter("pro");
			String detaildata = request.getParameter("detail");
			projectdata = projectdata.replaceAll("\"", "\\\"");
			projectDO = (NewProjectDO) JacksonUtil.json2Bean(projectdata, NewProjectDO.class);
			projectDO.setModifier(username);
			result = newproService.updateById(projectDO);
			if(result.isSucceed()){
				detaildata = detaildata.replaceAll("\"", "\\\"");
				detailDO = (NewProjectDetailDO) JacksonUtil.json2Bean(detaildata, NewProjectDetailDO.class);
				detailDO.setProjectId(projectDO.getId());
				if(detailDO.getOtherCost() == null){
					detailDO.setOtherCost(0L);
				}
				if(detailDO.getOtherCost() == 0){
					detailDO.setOtherDetail(null);
				}
				//新增 or 修改PROJECT DETAIL
				if(detailDO.getId() != null){
					detailDO.setModifier(username);
					result = newproDetailService.updateById(detailDO);
				}else{
					detailDO.setCreator(username);
					result = newproDetailService.insert(detailDO);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 返回结果
		return result;
	}
	
	/**
	 * 更新项目
	 * 
	 * @param projectDO
	 * @return
	 */
	@RequestMapping("/insert")
	@ResponseBody
	MessageResult<Long> insert(HttpServletRequest request) {
		MessageResult<Long> result = null;
		// 封装参数
		NewProjectDO projectDO = null;
		NewProjectDetailDO detailDO = null;
		try {
			String username = UserContext.getUsername();
			String projectdata = request.getParameter("pro");
			String detaildata = request.getParameter("detail");
			projectdata = projectdata.replaceAll("\"", "\\\"");
			projectDO = (NewProjectDO) JacksonUtil.json2Bean(projectdata, NewProjectDO.class);
			projectDO.setCreator(username);
			result = newproService.insert(projectDO);
			if(result.isSucceed()){
				detaildata = detaildata.replaceAll("\"", "\\\"");
				detailDO = (NewProjectDetailDO) JacksonUtil.json2Bean(detaildata, NewProjectDetailDO.class);
				detailDO.setProjectId(projectDO.getId());
				detailDO.setCreator(username);
				if(detailDO.getOtherCost() == null){
					detailDO.setOtherCost(0L);
				}
				result = newproDetailService.insert(detailDO);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 返回结果
		return result;
	}
	
	//ADD BY ZOE for JQUERY AUTOCOMPELETE
	@RequestMapping("/autoFillProjct")
	@ResponseBody
	public String autoFillProjct(@RequestParam String q, HttpServletResponse response){
		String responseStr = null;
		response.setCharacterEncoding("UTF-8");
		q = q.toUpperCase();
		Map<Object, Object> paramMap = new HashMap<Object, Object>();
		try {
			q = URLDecoder.decode(q,"UTF-8");
			paramMap.put("name", q);
			List<NewProjectDO> resultLst = newproService.selectList(paramMap);
			PrintWriter writer = response.getWriter();
			List<Map<String, String>> res = new ArrayList<Map<String,String>>();
			Map<String, String> map = null;
			for(NewProjectDO projectDO : resultLst){
				map = new HashMap<String, String>();
				map.put("id", projectDO.getId()+"");
				map.put("name", projectDO.getName());
				res.add(map);
			}
			ObjectMapper mapper = new ObjectMapper();
			mapper.writeValue(writer, res);
			responseStr = writer.toString();
			writer.write(responseStr);
			writer.flush();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
